package com.zjsru.plan2023.oneday;

import java.util.Arrays;

/**
 * @Author: CookLee
 * @Date: 2023/8/10
 * 给定行和列的和求可行矩阵
 * \
 * 输入：rowSum = [3,8], colSum = [4,7]
 * 输出：[[3,0],
 *       [1,7]]
 * 解释：
 * 第 0 行：3 + 0 = 3 == rowSum[0]
 * 第 1 行：1 + 7 = 8 == rowSum[1]
 * 第 0 列：3 + 1 = 4 == colSum[0]
 * 第 1 列：0 + 7 = 7 == colSum[1]
 * 行和列的和都满足题目要求，且所有矩阵元素都是非负的。
 * 另一个可行的矩阵为：[[1,2],
 *                   [3,5]]
 */
public class RestoreMatrix {
    
    /**
     * 贪心
     *
     * @param rowSum 行和
     * @param colSum 上校和
     * @return {@link int[][]}
     */
    public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
        int rowLength = rowSum.length;
        int colLength = colSum.length;
        int[][] ans = new int[rowLength][colLength];
        int i = 0, j = 0;
        while (i < rowLength && j < colLength) {
            int number = Math.min(rowSum[i], colSum[j]);
            rowSum[i] -= number;
            colSum[j] -= number;
            ans[i][j] = number;
            if (rowSum[i] == 0) {
                i++;
            } else if (colSum[j] == 0) {
                j++;
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        RestoreMatrix restoreMatrix = new RestoreMatrix();
        int[] rowSum = new int[] {3, 8};
        int[] colSum = new int[] {4, 7};
        System.out.println(Arrays.deepToString(restoreMatrix.restoreMatrix(rowSum, colSum)));
    }
}
